#!/bin/bash

set -x
LOG=/etc/supervisord.d/log

init() {
  #  查看supervisor是否存在
  pid=`ps -ef | grep "supervisord" | grep -v "grep" |  awk '{print $2}'`
  if [ "pid$pid" == "pid" ]; then
    echo "Supervisor not found, please install supervisor"
    return
  fi
  # 检查supervisor日志文件夹是否存在
  if [ ! -d $LOG ]; then
      mkdir -p ${LOG}
      chmod -R 755 $LOG
  fi

  # 解压整个文件
  cd /app
  tar -xvf bird-airport.tar.gz
  rm -rf bird-airport.tar.gz
  # 解压每个服务的文件夹
  cd bird-airport
  tar -xvf base-service.tar.gz
  chmod +x base-service/base-service
  rm -rf base-service.tar.gz
  tar -xvf bird-service.tar.gz
  chmod +x bird-service/bird-service
  rm -rf bird-service.tar.gz
  tar -xvf transfer-service.tar.gz
  chmod +x transfer-service/transfer-service
  rm -rf transfer-service.tar.gz
  tar -xvf media-service.tar.gz
  chmod +x media-service/media-service
  rm -rf media-service.tar.gz
  tar -xvf gateway-service.tar.gz
  chmod +x gateway-service/gateway-service
  rm -rf gateway-service.tar.gz

  # 复制supervisord.d脚本到etc
  cp -rf supervisord.d/* /etc/supervisor/conf.d/
  supervisorctl update

  echo "All services have been started."

}

stop() {
  echo "Stop base-service..."
  supervisorctl stop base-service

  echo "Stop bird-service..."
  supervisorctl stop bird-service

  echo "Stop transfer-service..."
  supervisorctl stop transfer-service

  echo "Stop media-service..."
  supervisorctl stop media-service

  echo "Stop gateway-service..."
  supervisorctl stop gateway-service

  echo "All services have been stop."
}

start() {
  # 启动Supervisor管理的服务
  echo "Starting base-service..."
  supervisorctl start base-service

  echo "Starting bird-service..."
  supervisorctl start bird-service

  echo "Starting transfer-service..."
  supervisorctl start transfer-service

  echo "Starting media-service..."
  supervisorctl start media-service

  echo "Starting gateway-service..."
  supervisorctl start gateway-service

  echo "All services have been started."
}

case "$1" in
stop)
  stop
  ;;
start)
  start
  ;;
init)
  init
  ;;
restart)
  stop
  start
  ;;
*)
  echo "Usage: $0 {stop|start|init|restart}"
  ;;
esac

